package ro.myApp.articles.client;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import ro.myApp.articles.dto.PublicationFindByIdMessage;
import ro.myApp.articles.entities.Publication;
import ro.myApp.client.BaseView;
import ro.myApp.client.helpers.PDFUtils;

@Name("documentViewer")
@BypassInterceptors
@Scope(ScopeType.PAGE)
public class DocumentViewer extends BaseView {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5151373323077158819L;

	private Long searchId;
	
	private Publication document;

	private int page = 0;
	
	private int totalPages = 0;
	
	private int zoom = 100;
	
	private byte[] image;
	
	public Long getSearchId() {
		return searchId;
	}
	
	public void setSearchId(Long searchId) {
		this.searchId = searchId;
	}
	
	public void firstPage (){
		page=0;
	}
	
	public void prevPage (){
		if (page > 0) {
			page--;
			refresh();
		}
	}
	
	public void nextPage (){
		if (totalPages > page + 1) {
			page++;
			refresh();
		}
	}
	
	public void lastPage (){
		if (totalPages > 1) {
			page = totalPages - 1;
			refresh();
		}
	}
	
	public int getPage (){
		return page;
	}
	
	public void setPage (int page){
		if (this.page!=page && page<=totalPages && page>0){
			this.page=page;
			refresh();
		}
	}
	
	public int getTotalPages (){
		return totalPages;
	}
	
	public void zoomIn (){
		if (zoom+10<1000)
			zoom+=10;
	}
	
	public void zoomOut (){
		if (zoom-10>10)
			zoom-=10;
	}
	
	public int getZoom() {
		return zoom;
	}
	
	public byte[] getImage (){
		return image;
	}
	
	public void init (){
		if (null==document){
			document = sendMessage (new PublicationFindByIdMessage(searchId));
			refresh();
		}
	}
	
	private void refresh (){
		try {
			image = PDFUtils.blobPdfToPageImage(document.getDocument(), page, zoom);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
